package logic

import (
	"context"
	"fmt"
	"novel/model/cache"
	"novel/model/mysql"

	"novel/novelrpc/internal/svc"
	"novel/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateLogic) Update(in *novelrpc.UpdateRequest) (*novelrpc.UpdateResponse, error) {
	// todo: add your logic here and delete this line
	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Account).Result()
	if result != in.SendSms {
		return nil, fmt.Errorf("验证码错误")
	}
	var user mysql.User
	mysql.DB.Debug().Where("account = ?", in.Account).Find(&user)
	if user.ID == 0 {
		return nil, fmt.Errorf("当前账号不存在")
	}

	user.Password = in.Password
	mysql.DB.Debug().Updates(&user)
	return &novelrpc.UpdateResponse{
		UserId: int64(user.ID),
	}, nil
}
